# -*- coding: utf-8 -*-
"""
--------------------------------------------
    Author:  niuqt
    Date:  8/16/2022 
--------------------------------------------
"""


# 查询所有主机
import os

from django.core.paginator import Paginator
from django.http import JsonResponse

from app01 import models
from app01.rsacrypto import RsaCrypto


def selectAllHosts(request):
    nowPage = request.GET.get("page")
    limit = request.GET.get("limit")
    if limit == "":
        limit = 5

    alluser_list = models.RemoteHost.objects.values()
    paginator = Paginator(list(alluser_list), int(limit))
    # print(list(alluser_list))
    if int(nowPage) >= int(paginator.num_pages):
        nowPage = paginator.num_pages
    try:
        page = paginator.page(nowPage)
    except:
        page = paginator.page(paginator.num_pages)

    data = {'data': list(page), 'code': "200", 'count': paginator.count, 'page': page.number, 'limit': page.__len__(),
        'pages': paginator.num_pages

    }
    return JsonResponse(data)  # 返回所有的数据，和每页显示多好行，以及页数的设置


# 主机页面 显示 远程用户 信息
def remoteusershow(request):
    allremoteUser = models.RemoteUser.objects.values()
    data = {'data': list(allremoteUser)}   #  元组 转列表

    return JsonResponse(data)



def addhostclass(request):

    if request.method == 'POST':
        hostname = request.POST.get("hostname", None)  # 获取html传过来的值
        ip = request.POST.get("ip", None)
        port = request.POST.get("port", None)
        protocol = request.POST.get("protocol", None)

        remoteuser = request.POST.get("remoteuser", None)

        if models.RemoteHost.objects.create(hostname=hostname, ip=ip, port=port,
                                               protocol=protocol,remote_user_id=remoteuser):
            return JsonResponse({"code": 200, "msg": "添加成功"}, safe=False)
        else:
            return JsonResponse({"code": 300, "msg": "添加失败"}, safe=False)







# 修改机器
def edithost(request):
    if request.method == 'POST':

        hostname = request.POST.get("hostname", None)
        ip = request.POST.get("ip", None)
        protocol = request.POST.get("protocol", None)

        remoteuser = request.POST.get("remoteuser", None)
        id = request.POST.get("id", None)

        # print(user_name,user_email,user_is_active,user_is_superuser,userid)

        # id ,为表中的字段名，这个要注意
        if models.RemoteHost.objects.filter(id=id).update(hostname=hostname, ip=ip,
                                                            protocol=protocol, remote_user_id=remoteuser):

            return JsonResponse({"code": 200, "msg": "修改成功"}, safe=False)
        else:
            return JsonResponse({"code": 300, "msg": "修改失败"}, safe=False)




# 批量删除  主机
def host_delete_all(request):
    # 先判断发过来的是否是post请求
    if request.method == "POST":
        # 得到要删除的ids列表 值
        values = request.POST.getlist('ids')

        new_list = values[0].split(',')

        for i in range(len(new_list)):
            # 如果id不为空，获取该字段，并将其删除，我们只删除book表，publisher表不变
            deleteID = int(new_list[i])
            book_obj = models.RemoteHost.objects.get(id=deleteID)
            book_obj.delete()
        # 删除成功返回显示页
        # return redirect('/curd/')
        data = {

            'code': "200",

        }
        return JsonResponse(data)


# 模糊查询 主机
def searchhost(request):
    host_name = request.GET.get("host_name")

    nowPage = request.GET.get("page")
    limit = request.GET.get("limit")

    # print(user_email,user_name)
    if limit == "":
        limit = 5

    if host_name != "":
        user_list = models.RemoteHost.objects.values().filter(hostname__contains=host_name)

    paginator = Paginator(list(user_list), int(limit))

    if int(nowPage) >= int(paginator.num_pages):
        nowPage = paginator.num_pages
    try:
        page = paginator.page(nowPage)
    except:
        page = paginator.page(paginator.num_pages)
    data = {'data': list(page), 'code': "200", 'count': paginator.count, 'page': page.number, 'limit': page.__len__(),
        'pages': paginator.num_pages

    }
    return JsonResponse(data)


####  远程用户

# 显示所有
def selectremoteuser(request):
    nowPage = request.GET.get("page")
    limit = request.GET.get("limit")
    if limit == "":
        limit = 5

    alluser_list = models.RemoteUser.objects.values()
    paginator = Paginator(list(alluser_list), int(limit))
    # print(list(alluser_list))
    if int(nowPage) >= int(paginator.num_pages):
        nowPage = paginator.num_pages
    try:
        page = paginator.page(nowPage)
    except:
        page = paginator.page(paginator.num_pages)

    data = {'data': list(page), 'code': "200", 'count': paginator.count, 'page': page.number, 'limit': page.__len__(),
        'pages': paginator.num_pages

    }
    return JsonResponse(data)  # 返回所有的数据，和每页显示多好行，以及页数的设置

# 添加
def addremoteuserclass(request):

    if request.method == 'POST':
        name = request.POST.get("name", None)  # 获取html传过来的值
        username = request.POST.get("username", None)
        password = request.POST.get("password", None)

        result = models.RemoteUser.objects.filter(name = name).exists()   # 判断 name是不是 有重复的
        if result:
            return JsonResponse({"code": 300, "msg": "显示名称重复"}, safe=False)
        else:
            password_encrypt = RsaCrypto().encrypt(password)['message']  # 密码加密

            if models.RemoteUser.objects.create(name=name, username=username, password=password_encrypt):
                return JsonResponse({"code": 200, "msg": "添加成功"}, safe=False)
            else:
                return JsonResponse({"code": 300, "msg": "添加失败"}, safe=False)



# 修改
def editremoteuser(request):
    if request.method == 'POST':

        name = request.POST.get("name", None)
        username = request.POST.get("username", None)
        password = request.POST.get("password", None)

        # name ,为表中的字段名，这个要注意
        password_encrypt = RsaCrypto().encrypt(password)['message']  # 密码加密
        if models.RemoteUser.objects.filter(name=name).update(username=username, password=password_encrypt):

            return JsonResponse({"code": 200, "msg": "修改成功"}, safe=False)
        else:
            return JsonResponse({"code": 300, "msg": "修改失败"}, safe=False)



# 批量删除
def remoteuser_delete_all(request):
    # 先判断发过来的是否是post请求
    if request.method == "POST":
        # 得到要删除的ids列表 值
        values = request.POST.getlist('names')

        new_list = values[0].split(',')
        fail_list = []   # 定义一个 列表，用来存放  删除失败的 远程用户显示名称

        for i in range(len(new_list)):
            # 如果id不为空，获取该字段，并将其删除，我们只删除book表，publisher表不变
            deleteName = new_list[i]

            # 通过 和 远程主机表 协同，确认 要删除的  远程用户显示 名称有没有 在 RemoteHost 表中 存在
            user_host_gx = models.RemoteHost.objects.filter(remote_user_id=deleteName).exists()
            if user_host_gx:
                fail_list.append(deleteName)   # 如果存在，则 把 要删除的 远程用户显示 名称 加入到 fail_list 列表中
                pass   # 直接通过，不显示 删除 异常 报错
            else:
                 models.RemoteUser.objects.get(name=deleteName).delete()  # 没在RemoteHost 表中 存在，则直接删除
                # print(book_obj.delete())  # (1, {'app01.RemoteUser': 1})
        # 判断 如果fail_list 列表 长度 大于0 ，说明要删除的用户有在RemoteHost 表中存在
        if len(fail_list) > 0:
            fail_name_all = ''  # 定义一个 字符串，用来 存所有 删除失败的 远程用户 显示名
            for i in range(len(fail_list)):
                # 如果id不为空，获取该字段，并将其删除，我们只删除book表，publisher表不变
                fail_name_temp = fail_list[i]
                fail_name_all = fail_name_temp + ", " + fail_name_all   # 遍历 fail_list 列表，把 所有 删除 失败的用户显示名 存放到 fail_name_all 字符串中
            msg_temp = fail_name_all + " 有绑定远程主机！ 其余删除成功~"
            data = {
                'code': "200",
                'msg': msg_temp
            }
            return JsonResponse(data)
        else:
            data = {
                'code': "200",
                'msg': "所选都删除成功~"
            }
            return JsonResponse(data)



# 通过传过来的用户 id  获取 用户名和密码
def websshup(request):
    if request.method == "POST":
        # 得到要删除的ids列表 值
        user_name = request.POST.get('rusername')
        # print(user_name)
        # print(sno)
        list_temp =  (list(models.RemoteUser.objects.filter(name=user_name).values()))[0]
        # {'name': 'root2', 'username': 'root', 'password': 'P@ssword', 'create_time': datetime.datetime(2022, 8, 16, 16, 22, 12, tzinfo=<UTC>)}
        # print(list_temp[0]['username'] )
        r_user = list_temp['username']
        r_password = list_temp['password']
        r_password_decrypt = RsaCrypto().decrypt(r_password)['message']  #  解密 password

        data = {
            'r_user': r_user,
            'r_password': r_password_decrypt,
            'aseKey': 'P@ssw0rd!@#$..12',    # 秘钥必须为：8/16/32位   URL跳转加密
        }

        return JsonResponse(data)


# 通过传过来的用户 id  获取 用户名和密码
def resKey(request):
    if request.method == "POST":
        # 得到要删除的ids列表 值

        data = {
            'aseKey': 'P@ssw0rd!@#$..12',  # 秘钥必须为：8/16/32位
        }

        return JsonResponse(data)



# 显示所有日志
def selectweblog(request):
    nowPage = request.GET.get("page")
    limit = request.GET.get("limit")
    if limit == "":
        limit = 5

    alluser_list = models.TerminalLog.objects.values()
    paginator = Paginator(list(alluser_list), int(limit))
    # print(list(alluser_list))
    if int(nowPage) >= int(paginator.num_pages):
        nowPage = paginator.num_pages
    try:
        page = paginator.page(nowPage)
    except:
        page = paginator.page(paginator.num_pages)

    data = {'data': list(page), 'code': "200", 'count': paginator.count, 'page': page.number, 'limit': page.__len__(),
        'pages': paginator.num_pages

    }
    return JsonResponse(data)  # 返回所有的数据，和每页显示多好行，以及页数的设置

# 批量删除  日志
def log_delete_all(request):
    # 先判断发过来的是否是post请求
    if request.method == "POST":
        # 得到要删除的ids列表 值
        values = request.POST.getlist('ids')
        new_list = values[0].split(',')

        for i in range(len(new_list)):
            # 如果id不为空，获取该字段，并将其删除，我们只删除book表，publisher表不变
            deleteID = int(new_list[i])
            log_obj = models.TerminalLog.objects.get(id=deleteID)
            video_time = models.TerminalLog.objects.filter(id=deleteID).values('video_lx_id')[0]['video_lx_id']

            log_obj.delete()
            vide_path_temp = "/" + models.LuXiangVideo.objects.filter(start_time=video_time).values('video_lx')[0]['video_lx']
            # vide_path_temp = "/data/830/adminlayui/" + models.LuXiangVideo.objects.filter(start_time=video_time).values('video_lx')[0]['video_lx']
            # os.remove(vide_path_temp)    # centos 可以使用、可能需要加上 项目的 实际 路径，

        # 删除成功返回显示页
        # return redirect('/curd/')
        data = {
            'code': "200",
        }
        return JsonResponse(data)



#  获取 录像的path
def lxpath(request):
    if request.method == "POST":
        # 得到要删除的ids列表 值
        log_id = request.POST.get('logid')
        # print(log_id)
        video_path_time = models.TerminalLog.objects.filter(id=log_id).values('video_lx_id')[0]['video_lx_id']
        # print(video_path_time)
        vide_path_temp = "/" + models.LuXiangVideo.objects.filter(start_time=video_path_time).values('video_lx')[0]['video_lx']

        # print(vide_path_temp)
        data = {
            'lxpathtemp': vide_path_temp,

        }
        return JsonResponse(data)




# 图表 测试
def tubiao1(request):
    if request.method == "POST":
        # 获取当前项目所有的目录: data = QuerySet类型
        riqi = models.tubiao1.objects.values_list('riqi',flat=True)  # 获取riqi 字段的所有值元组,使用values_list,注：不加list()会返回QuerySet
        # print(riqi)
        # print(list(riqi))
        riqi_data = models.tubiao1.objects.values_list('data_day', flat=True)
        data = {
            'riqilist': list(riqi),  # # JsonResponse在内部会调用json.dumps但是一个queryset是不能不序列化的 我们简单的做法就是将queryset转化成list
            'datalist': list(riqi_data),

        }
        return JsonResponse(data)


